#!/bin/bash

HOSTS_FILE_WIN='/mnt/c/Windows/System32/drivers/etc/hosts'
#inetIp=$(ifconfig eth0 | grep -o "inet [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*  netmask" | cut -f 2 -d " ")     # 获取本机ip
#nu=$(cat -n ${HOSTS_FILE_WIN} | grep wsl2host | awk '{print $1}')                                      # 获取已设置dns行号
#dnsIp=$(cat ${HOSTS_FILE_WIN} | grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]* wsl2host #" | cut -f 1 -d " ") # 获取已设置dns ip
#set -e
#if [ ${nu} ]; then # 若已设置
#  echo reset
#  sed -i "${nu}d" ${HOSTS_FILE_WIN}                              # 删除对应行
#  echo "${inetIp} wsl2host #wsl2 dns config" >>${HOSTS_FILE_WIN} # 重新设置
#else                                                             # 未设置
#  echo "${inetIp} wsl2host #wsl2 dns config" >>${HOSTS_FILE_WIN} # 直接设置
#fi
inetIp=$(ifconfig eth0 | grep -o "inet [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*  netmask" | cut -f 2 -d " ")     # 获取本机ip
nu=$(cat -n ${HOSTS_FILE_WIN} | grep wsl2host | awk '{print $1}')                                      # 获取已设置dns行号
dnsIp=$(cat ${HOSTS_FILE_WIN} | grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]* wsl2host #" | cut -f 1 -d " ") # 获取已设置dns ip
set -e
if [ ${nu} ]; then # 若已设置
  echo reset
  sed -i "${nu}d" ${HOSTS_FILE_WIN}                              # 删除对应行
  echo "127.0.0.1 wsl2host #wsl2 dns config" >>${HOSTS_FILE_WIN} # 重新设置
else                                                             # 未设置
  echo "127.0.0.1 wsl2host #wsl2 dns config" >>${HOSTS_FILE_WIN} # 直接设置
fi
netmask3=240
ip1=$(echo ${inetIp} | cut -f 1 -d ".")
ip2=$(echo ${inetIp} | cut -f 2 -d ".")
ip3=$(echo ${inetIp} | cut -f 3 -d ".")
ip3_2=$(echo "obase=2;${ip3} " | bc)
netmask3_2=$(echo "obase=2;${netmask3} " | bc)
y3=$((2#${ip3_2} & 2#${netmask3_2}))
win10host=$(printf "%s.%s.%s.1" ${ip1} ${ip2} ${y3})
echo "${win10host} windows2host #win10 dns config" >>/etc/hosts
runlevel=$(systemctl get-default)
#根据systemctl get-default获取默认运行级别
run_num=0
if [ "${runlevel}" = "emergency.target" ]; then
  run_num=1
elif [ "${runlevel}" = "rescure.target" ]; then
  run_num=2
elif [ "${runlevel}" = "multi-user.target" ]; then
  run_num=3
elif [ "${runlevel}" = "other" ]; then
  run_num=4
elif [ "${runlevel}" = "graphical.target" ]; then
  run_num=5
elif [ "${runlevel}" = "reboot.target" ]; then
  run_num=6
elif [ "${runlevel}" = "shutdown.target" ]; then
  run_num=0
fi
for name in $(ls /etc/rc${run_num}.d); do
  echo "start do /etc/rc${run_num}.d/${name}"
  if [ "${name:0:1}" = "S" ]; then
    /etc/rc${run_num}.d/"${name}" start &
    sleep 0.5
  fi
  if [ "${name:0:1}" = "K" ]; then
    /etc/rc${run_num}.d/"${name}" stop &
    sleep 0.5
  fi
  echo "end do /etc/rc${run_num}.d/${name}"
done
